package com.gitee.fsmxm.thinking.in.concurrent.basic;

import java.util.List;
import java.util.Vector;
import java.util.concurrent.Semaphore;
import java.util.function.Function;

public class _06_Semaphore_ObjectPool<T> {

    /**
     * 对象池
     * 固定大小的对象池，用完释放
     * 用 Semaphore 实现限流，Vector 保证互斥
     */
    public static class ObjectPool<T> {

        List<T> pool;
        Semaphore semaphore;

        public ObjectPool(int size, T t) {
            pool = new Vector<>(size); // Vector 保证互斥
            for (int i = 0; i < size; i++) {
                pool.add(t);
            }
            semaphore = new Semaphore(size, true); // Semaphore 实现限流，size 流的大小
        }

        public <R> R exec(Function<T, R> function) throws InterruptedException {
            semaphore.acquire();
            T t = null;
            try {
                t = pool.remove(0);
                return function.apply(t);
            } finally {
                pool.add(t);
                semaphore.release();
            }
        }

    }

    public static void main(String[] args) throws InterruptedException {
        ObjectPool<Long> pool = new ObjectPool<>(10, 2L);
        String res = pool.exec(t -> {
            System.out.println(t);
            return "res: " + t;
        });
        System.out.println(res);
    }
}
